<template>
  <div class="team-detail">
    <el-row :gutter="20">
      <!-- 左侧团队信息 -->
      <el-col :span="16">
        <!-- 冲刺信息卡片 -->
        <el-card shadow="hover" class="sprint-card">
          <template #header>
            <div class="card-header">
              <h3>当前冲刺</h3>
              <div class="sprint-controls">
                <el-button
                  v-if="sprintInfo.status === 'ongoing'"
                  type="warning"
                  size="small"
                  @click="pauseSprint"
                >
                  暂停冲刺
                </el-button>
                <el-button
                  v-if="sprintInfo.status === 'paused'"
                  type="success"
                  size="small"
                  @click="resumeSprint"
                >
                  恢复冲刺
                </el-button>
                <el-button
                  v-if="
                    sprintInfo.status === 'ongoing' ||
                    sprintInfo.status === 'paused'
                  "
                  type="danger"
                  size="small"
                  @click="endSprint"
                >
                  结束冲刺
                </el-button>
                <el-button
                  type="primary"
                  size="small"
                  @click="openSprintDialog"
                >
                  新建冲刺
                </el-button>
              </div>
            </div>
          </template>

          <div v-if="sprintInfo.sprint_id" class="sprint-content">
            <div class="sprint-stats">
              <el-statistic
                title="目标时间"
                :value="sprintInfo.target_formatted || '00:00:00'"
                class="sprint-stat"
              />
              <el-statistic
                title="已完成"
                :value="sprintInfo.completed_formatted || '00:00:00'"
                class="sprint-stat"
              />
              <el-statistic
                title="我的贡献"
                :value="sprintInfo.user_contribution_formatted || '00:00:00'"
                class="sprint-stat"
              />
            </div>
            <div class="progress-section">
              <el-progress
                :percentage="sprintInfo.progress_percentage || 0"
                :stroke-width="20"
                :text-inside="true"
                :status="sprintInfo.progress_percentage >= 100 ? 'success' : ''"
              />
            </div>
            <!-- 快速记录学习时间 -->
            <div class="quick-record">
              <h4>快速记录学习时间</h4>
              <el-form :model="studyForm" inline>
                <el-form-item label="时长">
                  <el-time-picker
                    v-model="studyForm.duration"
                    format="HH:mm:ss"
                    value-format="HH:mm:ss"
                    placeholder="选择时长"
                  />
                </el-form-item>
                <el-form-item label="说明">
                  <el-input
                    v-model="studyForm.description"
                    placeholder="学习内容说明"
                    style="width: 200px"
                  />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="recordStudyTime">
                    记录
                  </el-button>
                </el-form-item>
              </el-form>
            </div>
          </div>
          <div v-else class="no-sprint">
            <el-empty description="暂无进行中的冲刺">
              <el-button type="primary" @click="openSprintDialog">
                开始新冲刺
              </el-button>
            </el-empty>
          </div>
        </el-card>

        <!-- 任务管理卡片 -->
        <el-card shadow="hover" class="tasks-card">
          <template #header>
            <div class="card-header">
              <h3>团队任务</h3>
              <el-button type="primary" @click="openTaskDialog">
                <el-icon><Plus /></el-icon>
                添加任务
              </el-button>
            </div>
          </template>

          <el-table :data="tasks" style="width: 100%">
            <el-table-column prop="title" label="任务名称" />
            <el-table-column label="预估时间" width="120">
              <template #default="{ row }">
                {{ row.estimated_formatted || "未设置" }}
              </template>
            </el-table-column>
            <el-table-column label="实际时间" width="120">
              <template #default="{ row }">
                {{ row.actual_formatted || "未完成" }}
              </template>
            </el-table-column>
            <el-table-column label="负责人" width="100">
              <template #default="{ row }">
                {{ row.assignee ? row.assignee.username : "未分配" }}
              </template>
            </el-table-column>
            <el-table-column label="状态" width="100">
              <template #default="{ row }">
                <el-tag :type="getStatusType(row.status)">
                  {{ getStatusText(row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150">
              <template #default="{ row }">
                <el-button
                  v-if="row.status === 'pending'"
                  type="primary"
                  size="small"
                  @click="startTask(row)"
                >
                  开始
                </el-button>
                <el-button
                  v-if="row.status === 'in_progress'"
                  type="success"
                  size="small"
                  @click="openCompleteTaskDialog(row)"
                >
                  完成
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>

      <!-- 右侧信息栏 -->
      <el-col :span="8">
        <!-- 团队成员贡献 -->
        <el-card shadow="hover" class="members-card">
          <template #header>
            <div class="card-header">
              <span>成员贡献排行</span>
            </div>
          </template>

          <div class="members-ranking">
            <div
              v-for="(member, index) in memberRankings"
              :key="member.user_id"
              class="member-rank-item"
            >
              <div class="rank-number">{{ index + 1 }}</div>
              <el-avatar :size="32" :src="member.avatar" />
              <div class="member-info">
                <div class="member-name">{{ member.username }}</div>
                <div class="contribution-time">
                  {{ member.total_formatted }}
                </div>
              </div>
              <el-tag
                v-if="member.role === 'creator'"
                size="small"
                type="warning"
              >
                创建者
              </el-tag>
            </div>
          </div>
        </el-card>

        <!-- 学习动态 -->
        <el-card shadow="hover" class="activities-card">
          <template #header>
            <div class="card-header">
              <span>学习动态</span>
              <el-button size="small" @click="refreshActivities"
                >刷新</el-button
              >
            </div>
          </template>

          <div class="activities-list">
            <div
              v-for="activity in activities"
              :key="activity.id"
              class="activity-item"
            >
              <el-avatar :size="24" :src="activity.avatar" />
              <div class="activity-content">
                <div class="activity-text">
                  <strong>{{ activity.username }}</strong>
                  {{ activity.content }}
                </div>
                <div v-if="activity.task_description" class="activity-desc">
                  {{ activity.task_description }}
                </div>
                <div class="activity-time">{{ formatTime(activity.time) }}</div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 添加任务对话框 -->
    <el-dialog v-model="taskDialogVisible" title="添加任务" width="500px">
      <el-form :model="taskForm" label-width="100px">
        <el-form-item label="任务名称" required>
          <el-input v-model="taskForm.title" />
        </el-form-item>
        <el-form-item label="任务描述">
          <el-input v-model="taskForm.description" type="textarea" :rows="3" />
        </el-form-item>
        <el-form-item label="预估时间">
          <el-time-picker
            v-model="taskForm.estimated_time"
            format="HH:mm:ss"
            value-format="HH:mm:ss"
            placeholder="预估完成时间"
          />
        </el-form-item>
        <el-form-item label="负责人">
          <el-select v-model="taskForm.assignee_id" placeholder="选择负责人">
            <el-option
              v-for="member in team.members"
              :key="member.id"
              :label="member.username"
              :value="member.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span>
          <el-button @click="taskDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitTask">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 完成任务对话框 -->
    <el-dialog
      v-model="completeTaskDialogVisible"
      title="完成任务"
      width="400px"
    >
      <el-form :model="completeTaskForm" label-width="100px">
        <el-form-item label="实际耗时">
          <el-time-picker
            v-model="completeTaskForm.actual_time"
            format="HH:mm:ss"
            value-format="HH:mm:ss"
            placeholder="实际完成时间"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span>
          <el-button @click="completeTaskDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="completeTask">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 设置目标对话框 -->
    <el-dialog v-model="sprintDialogVisible" title="设置冲刺目标" width="500px">
      <el-form :model="sprintForm" label-width="100px">
        <el-form-item label="目标学时" required>
          <el-input-number
            v-model="sprintForm.targetHours"
            :min="1"
            :max="168"
          />
          <span style="margin-left: 10px; color: #909399">小时</span>
        </el-form-item>
      </el-form>
      <template #footer>
        <span>
          <el-button @click="sprintDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="startNewSprint">开始冲刺</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from "vue";
import { useRoute } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { teamApi, teamUtils } from "@/api/team";
import { Plus } from "@element-plus/icons-vue";

const route = useRoute();
const team = ref({});
const tasks = ref([]);
const sprintInfo = ref({});
const memberRankings = ref([]);
const activities = ref([]);
const refreshCounter = ref(0);
// 对话框状态
const taskDialogVisible = ref(false);
const sprintDialogVisible = ref(false);
const completeTaskDialogVisible = ref(false);

// 表单数据
const taskForm = ref({
  title: "",
  description: "",
  estimated_time: "01:00:00",
  assignee_id: null,
});

const sprintForm = ref({
  targetHours: 20,
});

const studyForm = ref({
  duration: "00:30:00",
  description: "",
});

const completeTaskForm = ref({
  actual_time: "01:00:00",
});

const currentTask = ref(null);

// 自动刷新定时器
let refreshTimer = null;

// 获取团队详情
const fetchTeamDetail = async () => {
  try {
    const teamId = route.params.id;
    const response = await teamApi.getTeamDetail(teamId);
    team.value = response;
  } catch (error) {
    console.error("获取团队详情失败:", error);
    ElMessage.error("获取团队详情失败");
  }
};

// 获取任务列表
const fetchTasks = async () => {
  try {
    const teamId = route.params.id;
    const response = await teamApi.getTeamTasks(teamId);
    tasks.value = response;
  } catch (error) {
    console.error("获取任务列表失败:", error);
    ElMessage.error("获取任务列表失败");
  }
};

// 获取冲刺信息
const fetchSprintData = async () => {
  try {
    const teamId = route.params.id;
    const response = await teamApi.getSprintData(teamId);
    sprintInfo.value = response;
    memberRankings.value = response.member_rankings || [];
    activities.value = response.activities || [];
  } catch (error) {
    console.error("获取冲刺信息失败:", error);
  }
};

// 刷新所有数据
const refreshAll = async () => {
  await Promise.all([fetchTeamDetail(), fetchTasks(), fetchSprintData()]);
};

// 记录学习时间
const recordStudyTime = async () => {
  try {
    if (!studyForm.value.duration) {
      ElMessage.warning("请选择学习时长");
      return;
    }

    const seconds = teamUtils.parseDuration(studyForm.value.duration);
    if (seconds <= 0) {
      ElMessage.warning("学习时长必须大于0");
      return;
    }

    const teamId = route.params.id;
    await teamApi.recordStudyTime(teamId, {
      seconds,
      description: studyForm.value.description,
    });

    ElMessage.success("学习时间记录成功");

    // 重置表单
    studyForm.value = {
      duration: "00:30:00",
      description: "",
    };

    // 刷新数据
    await fetchSprintData();
  } catch (error) {
    console.error("记录学习时间失败:", error);
    ElMessage.error("记录学习时间失败");
  }
};

// 开始任务
const startTask = async (task) => {
  try {
    const teamId = route.params.id;
    await teamApi.startTask(teamId, task.id);
    ElMessage.success("任务已开始");
    await fetchTasks();
  } catch (error) {
    console.error("开始任务失败:", error);
    ElMessage.error("开始任务失败");
  }
};

// 打开完成任务对话框
const openCompleteTaskDialog = (task) => {
  currentTask.value = task;
  completeTaskForm.value.actual_time = task.estimated_formatted || "01:00:00";
  completeTaskDialogVisible.value = true;
};

// 完成任务
const completeTask = async () => {
  try {
    const actualSeconds = teamUtils.parseDuration(
      completeTaskForm.value.actual_time
    );
    const teamId = route.params.id;

    await teamApi.completeTeamTask(teamId, currentTask.value.id, actualSeconds);

    ElMessage.success("任务已完成");
    completeTaskDialogVisible.value = false;

    await Promise.all([fetchTasks(), fetchSprintData()]);
  } catch (error) {
    console.error("完成任务失败:", error);
    ElMessage.error("完成任务失败");
  }
};

// 添加任务
const submitTask = async () => {
  try {
    if (!taskForm.value.title) {
      ElMessage.warning("请输入任务名称");
      return;
    }

    const teamId = route.params.id;
    const data = {
      title: taskForm.value.title,
      description: taskForm.value.description,
      estimated_hours: teamUtils.secondsToHours(
        teamUtils.parseDuration(taskForm.value.estimated_time)
      ),
      assignee_id: taskForm.value.assignee_id,
    };

    await teamApi.createTeamTask(teamId, data);

    ElMessage.success("添加成功");
    taskDialogVisible.value = false;
    await fetchTasks();

    // 重置表单
    taskForm.value = {
      title: "",
      description: "",
      estimated_time: "01:00:00",
      assignee_id: null,
    };
  } catch (error) {
    console.error("添加任务失败:", error);
    ElMessage.error("添加任务失败");
  }
};

// 开始新的冲刺
const startNewSprint = async () => {
  try {
    const teamId = route.params.id;
    await teamApi.startSprint(teamId, {
      target_hours: sprintForm.value.targetHours,
    });

    ElMessage.success("冲刺开始");
    sprintDialogVisible.value = false;
    await fetchSprintData();
  } catch (error) {
    console.error("开始冲刺失败:", error);
    ElMessage.error("开始冲刺失败");
  }
};

// 暂停冲刺
const pauseSprint = async () => {
  try {
    const teamId = route.params.id;
    await teamApi.pauseResumeSprint(teamId, "pause");
    ElMessage.success("冲刺已暂停");
    await fetchSprintData();
  } catch (error) {
    console.error("暂停冲刺失败:", error);
    ElMessage.error("暂停冲刺失败");
  }
};

// 恢复冲刺
const resumeSprint = async () => {
  try {
    const teamId = route.params.id;
    await teamApi.pauseResumeSprint(teamId, "resume");
    ElMessage.success("冲刺已恢复");
    await fetchSprintData();
  } catch (error) {
    console.error("恢复冲刺失败:", error);
    ElMessage.error("恢复冲刺失败");
  }
};

// 结束冲刺
const endSprint = async () => {
  try {
    await ElMessageBox.confirm("确定要结束当前冲刺吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    const teamId = route.params.id;
    await teamApi.endSprint(teamId);
    ElMessage.success("冲刺已结束");
    await fetchSprintData();
  } catch (error) {
    if (error !== "cancel") {
      console.error("结束冲刺失败:", error);
      ElMessage.error("结束冲刺失败");
    }
  }
};

// 刷新活动
const refreshActivities = async () => {
  await fetchSprintData();
  ElMessage.success("已刷新");
};

// 工具函数
const getStatusText = (status) => teamUtils.getStatusText(status);
const getStatusType = (status) => teamUtils.getStatusType(status);

const formatTime = (timeString) => {
  const date = new Date(timeString);
  const now = new Date();
  const diff = now - date;

  if (diff < 60000) return "刚刚";
  if (diff < 3600000) return `${Math.floor(diff / 60000)}分钟前`;
  if (diff < 86400000) return `${Math.floor(diff / 3600000)}小时前`;
  return date.toLocaleDateString();
};

// 打开对话框
const openTaskDialog = () => {
  taskForm.value = {
    title: "",
    description: "",
    estimated_time: "01:00:00",
    assignee_id: null,
  };
  taskDialogVisible.value = true;
};

const openSprintDialog = () => {
  sprintForm.value = { targetHours: 20 };
  sprintDialogVisible.value = true;
};

// 设置自动刷新
const startAutoRefresh = () => {
  refreshTimer = setInterval(() => {
    fetchSprintData();
  }, 30000); // 每30秒刷新一次
};

const stopAutoRefresh = () => {
  if (refreshTimer) {
    clearInterval(refreshTimer);
    refreshTimer = null;
  }
};
const timer = ref(null);
function addOneSecond(timeStr) {
  // 将时间字符串分割成小时、分钟、秒
  const parts = timeStr.split(":");
  let hours = parseInt(parts[0], 10);
  let minutes = parseInt(parts[1], 10);
  let seconds = parseInt(parts[2], 10);

  // 增加1秒
  seconds += 1;

  // 处理进位
  if (seconds >= 60) {
    seconds = 0;
    minutes += 1;

    if (minutes >= 60) {
      minutes = 0;
      hours += 1;

      if (hours >= 24) {
        hours = 0;
      }
    }
  }

  // 将各部分格式化为两位数
  const format = (num) => num.toString().padStart(2, "0");

  return `${format(hours)}:${format(minutes)}:${format(seconds)}`;
}
const refreshTask = () => {
  tasks.value.forEach((i) => {
    if (i.actual_formatted && i.status === "in_progress") {
      i.actual_formatted = addOneSecond(i.actual_formatted);
    }
  });
};
onMounted(() => {
  refreshAll();
  startAutoRefresh();
  // 每秒更新一次
  timer.value = setInterval(() => {
    refreshTask();
  }, 1000);
});

onUnmounted(() => {
  stopAutoRefresh();
  clearInterval(timer.value);
});
</script>

<style scoped>
.team-detail {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
}

.sprint-card {
  margin-bottom: 20px;
}

.sprint-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.sprint-stats {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20px;
}

.sprint-stat {
  text-align: center;
}

.progress-section {
  margin: 20px 0;
}

.quick-record {
  padding: 16px;
  background: var(--el-fill-color-light);
  border-radius: 8px;
}

.quick-record h4 {
  margin: 0 0 16px 0;
  color: var(--el-text-color-primary);
}

.no-sprint {
  text-align: center;
  padding: 40px;
}

.tasks-card {
  margin-bottom: 20px;
}

.members-ranking {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.member-rank-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  border-radius: 8px;
  background: var(--el-fill-color-light);
}

.rank-number {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  background: var(--el-color-primary);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  font-weight: bold;
}

.member-info {
  flex: 1;
}

.member-name {
  font-weight: 500;
  color: var(--el-text-color-primary);
}

.contribution-time {
  font-size: 12px;
  color: var(--el-text-color-secondary);
}

.activities-card {
  margin-bottom: 20px;
}

.activities-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
  max-height: 400px;
  overflow-y: auto;
}

.activity-item {
  display: flex;
  gap: 8px;
  padding: 8px;
  border-radius: 4px;
  background: var(--el-fill-color-lighter);
}

.activity-content {
  flex: 1;
}

.activity-text {
  font-size: 14px;
  margin-bottom: 4px;
}

.activity-desc {
  font-size: 12px;
  color: var(--el-text-color-secondary);
  margin-bottom: 4px;
}

.activity-time {
  font-size: 12px;
  color: var(--el-text-color-placeholder);
}

.sprint-controls {
  display: flex;
  gap: 8px;
}
</style>
